﻿using DataServer.CommonLib.Models.ConfigData;
using DataServer.CommonLib.Models.DataConfig;
using FluentValidation;
using System.Linq.Expressions;

namespace DataServer.CommonLib.Validators
{
    public class ConfigDataEditValidator : AbstractValidator<ConfigDataEditRequestDto>
    {
        public ConfigDataEditValidator(IList<ConfigFieldInfoResponseDto> allFields)
        {
            //Expression<Func<ConfigDataEditRequestDto, string?>> expression = p => p.VarcharAttribute2;

            //RuleFor(expression).NotEmpty();

            foreach (var field in allFields)
            {
                var rule = RuleFor(ConvertStringProperty(field.ValueColumnMap));
                if (field.IsRequired)
                {
                    rule.NotEmpty();
                }
            }
        }

        private Expression<Func<ConfigDataEditRequestDto, string?>> ConvertStringProperty(string valueColumnMap)
        {
            ParameterExpression parameterExpression = Expression.Parameter(typeof(ConfigDataEditRequestDto), "p");
            MemberExpression memberExpression = Expression.Property(parameterExpression, valueColumnMap);
            Expression<Func<ConfigDataEditRequestDto, string?>> expression =
                Expression.Lambda<Func<ConfigDataEditRequestDto, string?>>(memberExpression, parameterExpression);

            return expression;
        }


        public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
        {
            var result =
                await ValidateAsync(ValidationContext<ConfigDataEditRequestDto>.CreateWithOptions((ConfigDataEditRequestDto)model,
                    x => x.IncludeProperties(propertyName)));
            if (result.IsValid)
                return Array.Empty<string>();
            return result.Errors.Select(e => e.ErrorMessage);
        };
    }


}
